<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>深拷贝多层次分析</title>
</head>
<body>
    <script>
        let hd = {
            name : '后盾人',
            tag : {
                name : "每天进步一点点"
            }
        };

        // 浅拷贝，属性值是引用类型时，两边还是会同时改变
        // let hdms = {};
        // for (const key in hd) {
        //     hdms[key] = hd[key];
        // }
        // console.log(JSON.stringify(hdms,null,2));
        // hdms.tag.name = "要爱自己";
        // console.log(JSON.stringify(hd,null,2));
        // console.log(JSON.stringify(hdms,null,2));



        // 深拷贝，属性值是引用类型时，使用迭代
        function copy(obj){
            let hdms = {};
            for (const key in obj) {
                hdms[key] = typeof obj[key] == 'object' ? copy(obj[key]) : obj[key];
            }
            return hdms;
        }
        let hdms = copy(hd);
        console.log(JSON.stringify(hdms,null,2));
        hdms.tag.name = "要爱自己";
        console.log(JSON.stringify(hd,null,2));
        console.log(JSON.stringify(hdms,null,2));




        // 深拷贝，对象的属性值既有对象又有数组
        let lessons = {
            name : "html",
            title : {
                name : "每天多看一点"
            },
            author : []
        };
        function deepcopy(obj){
            // 判断是否是数组
            let lesson = obj instanceof Array ? [] : {};    //用于迭代的时候判断
            for (const [key,value] of Object.entries(obj)) {
                lesson[key] = typeof value == 'object' ? deepcopy(value) : value;
            }
            return lesson;
        }
        let lesson = deepcopy(lessons);
        console.log(JSON.stringify(lesson,null,2));
        lesson.author.push('向军');
        console.log(JSON.stringify(lesson,null,2));
        console.log(JSON.stringify(lessons,null,2));
    </script>
</body>
</html>